package com.book.common;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @Author Jincheng.Li
 * @Date 2021/6/6 7:39 下午
 * @Project_Name graduation-project
 */
@Slf4j
@Aspect
@Component
@SuppressWarnings("all")
public class RepeatSubmitAspect {
    public static final String KEYPREX = "noRepeat:user:";

    @Autowired
    private RedisTemplate redisTemplate;

    @Around("execution(* com.book.controller.*.*(..)) && @annotation(noRepeatSubmit)")
    public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit noRepeatSubmit) throws Throwable{
        try {
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            StringBuilder sb = new StringBuilder();
            sb.append(KEYPREX).append(request.getHeader("token").toString()).append(request.getRequestURI().toString());
            log.info("noRepeatSubmit sb:{}",sb.toString());
            long now = System.currentTimeMillis();
            if (redisTemplate.hasKey(sb.toString())){
                long lastTime= Long.valueOf(redisTemplate.opsForValue().get(sb.toString()).toString()) ;
                if ((now - lastTime)>noRepeatSubmit.lockTime()){
                    redisTemplate.opsForValue().set(sb.toString(),String.valueOf(now),10, TimeUnit.MINUTES);
                    Object result =  pjp.proceed();
                    return result;
                }else {
                    return CommonResult.getFaiInstance(-1,"点击的太快了,请慢一点!");
                }
            }else {
                //第一次操作
                redisTemplate.opsForValue().set(sb.toString(),String.valueOf(now),10, TimeUnit.MINUTES);
                Object result =  pjp.proceed();
                return result;
            }
        }catch (Throwable e){
            log.error("校验表单重复提交时异常: {}", e.getMessage());
            return CommonResult.getFaiInstance(-1,"校验重复提交时异常");
        }
    }
}
